import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';
import CpasTableFs, { ImportToTitle } from '~/public/cpas-business/cpas-table/CpasTableFs';
import Details from '~/public/cpas-business/cpas-table/ExcelGrid/components/Validator/CheckDetails';

// import CpasTable from "~/public/cpas-business/cpas-table/ExcelGrid";
import PageLoading from '@/pages/components/PageLoading';
import '@/pages/components/StyleFile/btnStyle.less';
import { getSeekAuditReportTemplate } from '@/pages/reportBuilder/service';
import { CellsMetaUpdateCPASTableData, extractFileInfo, Md5_16, nanoid10 } from '@/utils';
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { Modal, Radio, Typography } from 'antd';
import axios from 'axios';
import BigNumber from 'bignumber.js';
import { Button, DataGrid, SelectBox } from 'devextreme-react';
import { Column, Paging, Scrolling, Selection } from 'devextreme-react/data-grid';
import DropDownButton from 'devextreme-react/drop-down-button';
import notify from 'devextreme/ui/notify';
import { Guid } from 'guid-factory/lib/Guid';
import { useModel } from 'umi';
import ChangeTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/ChangeTemplatePopup';
import SaveTemplatePopup from '~/public/cpas-business/components-bs/components/TemplatePopup/SaveTemplatePopup';
import { CpasIcon } from '~/public/cpas-ui';
import { pushNumberData } from '../../../../utils';
import CpasTableChangePupop from '../../../components/CpasTableChangePupop';
import PopupComponents from '../../../components/PopupComponents';
import { clearDynamicByMainTable, getfindDesignTableName } from '../service';
import './index.less';
import {
  batchClearData,
  batchClearGSData,
  batchVerifyRecal,
  getAccountInfo,
  getColumnsMapByReport,
  getCpasAllTids,
  getRowsMapByReport,
  gettableIsVerifyTid,
  getVerifyByRMap,
  getVerifyDataList,
  queryVerifyStatefs,
  reloadBatchDataRecalculateFs,
  saveTemplateApi,
  templateInitApi,
} from './service';

const { Paragraph } = Typography;

const CommonCpasTableSS = React.forwardRef((props: any, ref: any) => {
  const {
    CPASTableProps,
    excelParams,
    tableNameGroup,
    antTabsTabPaneDetail,
    cpasChangeSpinAntTabs,
    isInitBtn,
    changeIsInitBtn,
    getChangeyearInitTemplate,
    CPASTableTabName,
    radioVal,
    biaoAllData,
  } = props;
  const { templateKey, tableName, titleName, tabsIndex, tableRiCurrency } = CPASTableProps;
  const { initialState } = useModel('@@initialState');
  const { cpasTableZeroReplace, negationRow } = initialState?.settings;
  const { dbname, bsdw, sjnd, zcbfid } = initialState?.curPart as API.CurPart;
  const { pathname, query }: any = window.location || {};
  const [rowsMapList, setRowsMapList] = useState<any[]>([]);
  const [columnsMapList, setColumnsMapList] = useState<any[]>([]);
  const cpasTableFsRefSS = useRef<any>(null);
  const saveTemplatePopupRef = useRef<any>();
  const changeTemplatePopupRef = useRef<any>();
  const [showMenuToolBar, setShowMenuToolBar] = useState<boolean>(false);
  const [value, setValue] = useState(1);
  const [selectYearData, setSelectYearData] = useState<any>({
    yearStr: '',
    index: 0,
  });

  const slectYearDataRef = useRef<any>({
    yearStr: '',
    index: 0,
  });
  // const [titleYearStr, setTitleYearStr] = useState<string>(' ');
  const [cpasTableName, setCpasTableName] = useState<string>('');
  const [spinLoad, setSpinLoad] = useState<boolean>(false);
  const [serverDataLen, setServerDataLen] = useState<number>(2);
  const Divstyle: React.CSSProperties = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: '15px',
  };
  const showYaerData = useRef<any[]>([]);
  const cpasTableChangePupopRef = useRef<any>(null);
  // const [getYearTitleData, setGetYearTitleData] = useState<any[]>([]);
  const [loadingContent, setLoadingContent] = useState<string>('');
  const [openDetails, setOpenDetails] = useState<boolean>(false);
  const [resultListData, setResultListData] = useState<any>({
    verifyResult: [],
    isBackAll: false,
  });

  const cpasTableTid = useRef<any>(''); // tid
  const PopupComponentsRef = useRef<any>(null);

  const cpasTableAllRowsMapsData = useRef<any[]>([]); //
  const cpasTableVerifyData = useRef<any>({}); //
  const [isShowOpenModal, setIsShowOpenModal] = useState<boolean>(false);
  const [isModalTableData, setIsModalTableData] = useState<any[]>([]);
  const [selectedKey, setSelectedKey] = useState<any[]>([]);
  const [selectedRowData, setSelectedRowData] = useState<any>({});

  // 拼接数组 生成字符串的函数  未审财务数据
  const joinArrar = (arr: any) => {
    const arrData = arr.join('],[').replaceAll(' ', '');
    return `[${arrData}]`;
  };

  //注意mapList接收的映射源为数组结构(handson所决定) [,,,]
  function dataObjToArray(objData: any[]) {
    const result = [''];
    objData.forEach((item) => {
      result.push(item.value);
    });
    return result;
  }

  // 获取真是的CPASTable的ref
  const getRealCPASTableRef = () => {
    if (cpasTableFsRefSS.current) {
      const realHandSonGridRef = cpasTableFsRefSS.current.handsonTableFs.current;
      return realHandSonGridRef;
    }
    return null;
  };

  //初始化表格映射数据源
  async function loadRowsMapData() {
    const rowsMapListData = await getRowsMapByReport({ dbname });
    setRowsMapList(dataObjToArray(rowsMapListData.data));
  }
  //初始化表格映射数据源
  async function loadColumnsMapData() {
    const columnsMapListData: any = await getColumnsMapByReport({ dbname });
    setColumnsMapList(dataObjToArray(columnsMapListData.data));
  }

  // 业务要加那个预制校验
  const changeCrticulationVerify = async (dataRef: any) => {
    const verifyResult = dataRef.articulationVerifyService.artParseResultList;
    const formulaList = dataRef.articulationVerifyService.artVerifyFormulaList;
    const parseList = await dataRef.articulationVerifyService.parseArtVerifyFormula(formulaList);
    // 增加 单点标志值 默认 []
    const resultItem = dataRef.articulationVerifyService?.artResultItem;
    if (!resultItem) return;
    if (resultItem?.length > 0) {
      dataRef.articulationVerifyService.markBeVerifiedItem(resultItem[0], true, true);
    } else if (verifyResult.length > 0) {
      dataRef.articulationVerifyService.batchMarkBeVerifiedItem(parseList);
    }
  };

  const getAllRowsMaps = (data: any[]) => {
    const result = [...data.map((item) => item[0])];
    result.shift();
    return result;
  };

  /**
   * 进来之后加载数据的函数。
   * @param serverName 请求的表名
   * @returns
   */
  const loadTableByServerData = async (serverName: string) => {
    setSpinLoad(true);
    let serverData: any;
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      try {
        // console.time();
        serverData = await realrealHandSonGridRefRef.loadTableByServer(serverName);
        console.log('--------serverData初始数据@@@', serverData);
        if (serverData.data) {
          const res = await gettableIsVerifyTid({
            tableName: serverName,
            dbname,
            isTid: true,
          });
          if (res.success && res.data?.length) {
            cpasTableTid.current = res.data[0].tid;
            const tid = res.data[0].tid;
            // const verifyData = await realrealHandSonGridRefRef.loadVerifyByServer(tid);
            const verifyData = await realrealHandSonGridRefRef.loadVerifyByServer(tid);
            const fsParams = {
              dbname,
              tid: tid,
              type: 'fs',
            };
            const lodaTableZl = await queryVerifyStatefs(fsParams);
            if (lodaTableZl.code === 200) {
              realrealHandSonGridRefRef.setVerifyData(verifyData);
              setResultListData({
                verifyResult: verifyData.artParseResultList,
                isBackAll: false,
              });
            }
            cpasTableAllRowsMapsData.current = getAllRowsMaps(serverData.data);
            const resByRMap = await getVerifyByRMap({
              dbname,
              dataId: slectYearDataRef.current.yearStr,
              tid: tid,
            });
            cpasTableVerifyData.current = resByRMap.data;
            serverData.cellsMeta = CellsMetaUpdateCPASTableData(
              serverData.cellsMeta,
              cpasTableAllRowsMapsData.current,
              resByRMap.data,
            );
          } else {
            notify(`获取tid失败！`, 'error', 2000);
          }
          await realrealHandSonGridRefRef.reloadTable(serverData, 'fs', null, true);
          await changeCrticulationVerify(realrealHandSonGridRefRef);
          await antTabsTabPaneDetail(slectYearDataRef.current.yearStr);
          setServerDataLen(serverData.data.length);
          setSpinLoad(false);
          notify(`获取该表数据成功！`, 'success', 2000);
          return {
            data: serverData,
            msg: serverData.msg,
            success: true,
          };
        } else {
          setServerDataLen(2);
          // notify(`获取数据失败：${serverData.msg}！`, "warning", 2000);
          setSpinLoad(false);
          realrealHandSonGridRefRef.resetTable('fs');
          notify(`获取数据失败：${serverData.msg}！`, 'warning', 2000);
          return {
            data: [],
            msg: serverData.msg,
            success: false,
          };
        }
      } catch (e) {
        setServerDataLen(2);
        notify(`没有该表:【${serverName}】的数据！`, 'warning', 2000);
        setSpinLoad(false);
        realrealHandSonGridRefRef.resetTable('fs');
        return {
          data: [],
          msg: serverData.msg,
          success: false,
        };
      }
    }
    return;
  };

  /**
   * 获取年度的函数
   */
  const fetchYearData = useCallback(async () => {
    const auditAdjustId: any = window.localStorage.getItem(`selectDefaultSsph_${dbname}`);
    const tempYear = JSON.parse(auditAdjustId)?.ssphYearID ?? sjnd;
    let findTemp = -2;

    const res = await getAccountInfo({ dbname });
    if (res.success && res.data?.length) {
      res.data.forEach((item: any, ind: any) => {
        item.index = ind;
        return item;
      });
      findTemp = res.data.findIndex((item: any) => {
        return tempYear === item.Data_ID;
      });
      const tempIndex = findTemp >= 0 ? findTemp : 0;
      const DataId = res.data[tempIndex]?.Data_ID;
      // const tempDisplayName = res.data[tempIndex]?.displayName;
      showYaerData.current = res.data;
      return {
        data: {
          yearStr: DataId,
          index: tempIndex,
        },
        success: true,
      };
    } else {
      notify(`获取年度数据报错！`, 'error', 2000);
      return {
        data: {
          yearStr: '',
          index: 0,
        },
        success: false,
      };
    }
  }, []);

  const joinYearAndTable = (joinYear: string, jointableName: string) => {
    const yearTableName = `${joinYear}_${jointableName}`;
    setCpasTableName(yearTableName); // 更改cpasTableName的值
    return yearTableName;
  };

  const fetchGetYearData = async () => {
    const resYaer = await fetchYearData();
    if (resYaer.success) {
      const realYear = resYaer.data;
      setSelectYearData(realYear);
      joinYearAndTable(realYear.yearStr, tableName);
      slectYearDataRef.current.index = realYear.index;
      slectYearDataRef.current.yearStr = realYear.yearStr;
      setSpinLoad(false);
      return {
        data: {
          yearStr: realYear.yearStr,
          index: realYear.index,
        },
        success: true,
      };
    }
    return {
      data: {
        yearStr: '',
        index: 0,
      },
      success: false,
    };
  };

  // const reloadServerData = async (serverName: string) => {
  //     loadRowsMapData();
  //     loadColumnsMapData();
  //     let serverData: any;
  //     const realrealHandSonGridRefRef = getRealCPASTableRef();
  //     if (realrealHandSonGridRefRef) {
  //         try {
  //             serverData = await realrealHandSonGridRefRef.loadTableByServer(serverName);
  //         } catch (e) {
  //             notify(`没有该表:【${serverName}】的数据！`, "warning", 2000);
  //             realrealHandSonGridRefRef.resetTable('fs');
  //             serverData = { serverCpasTableData: {} }
  //         }
  //     }
  //     return serverData;
  // }

  // // 刷新
  // const cpasTableReloadAudio = async () => {
  //     if (!slectYearDataRef.current.yearStr) return notify(`年度数据为空，禁止刷新！`, "error", 2000);
  //     let serverCpasTableData: any;
  //     if (cpasTableName) {
  //         serverCpasTableData = await reloadServerData(cpasTableName);
  //     }
  //     console.log('------loadTableByServerData数据@@@------', cpasTableName, serverCpasTableData);
  //     if (!serverCpasTableData) return notify(`没有该表:【${cpasTableName}】的数据！`, "error", 2000);
  //     try {
  //         const realrealHandSonGridRefRef = getRealCPASTableRef();
  //         if (realrealHandSonGridRefRef) {

  //             setLoadingContent('刷新中...');
  //             setSpinLoad(true);
  //             const result = realrealHandSonGridRefRef.getCurrentTableMaps();
  //             const colsArray = joinArrar(result.cmaps);
  //             const keysArray = joinArrar(result?.rmaps);
  //             // const resCol = colsArray.includes('[]');
  //             // const resKey = keysArray.includes('[]');
  //             // if (resCol || resKey) {
  //             //     setSpinLoad(false);
  //             //     return notify(`请核对表头对应关系！`, "warning", 2000);
  //             // }
  //             const res = await getSsphData({
  //                 dbname,
  //                 data_ID: slectYearDataRef.current.yearStr,
  //                 cols: colsArray,
  //                 keys: keysArray
  //             });
  //             if (res.success) {
  //                 const cpasData = UpdateCPASTableData(res.data, serverCpasTableData.data, 2, negationRow, slectYearDataRef.current.yearStr);
  //                 serverCpasTableData.data = cpasData;
  //                 console.log('------插入data之后的数据 cpasData  - 数据@@@------', res.data, cpasData, serverCpasTableData);
  //                 await realrealHandSonGridRefRef.reloadTable(serverCpasTableData, 'fs', null, true)
  //                 console.log("执行重算");
  //                 await realrealHandSonGridRefRef.reCalculateFormula();
  //                 changeCrticulationVerify(realrealHandSonGridRefRef);
  //                 setServerDataLen(serverCpasTableData.data.length);
  //                 setSpinLoad(false);
  //                 notify(`刷新成功！`, "success", 2000);
  //             } else {
  //                 setSpinLoad(false);
  //                 notify(res.data, "error", 2000);
  //             }
  //         }
  //     } catch (error) {
  //         setSpinLoad(false);
  //         notify(`刷新失败！`, "warning", 2000);
  //     }
  // }

  const onRadioChangeFor = (ItmeTableName: any, ItmeTemplateKey: string) => {
    const tempData = ItmeTableName.split('_');
    let tempName1: string = '';
    let tempName2: string = '';
    if (ItmeTemplateKey === 'qmqc') {
      tempName1 = `${tempData[0]}_期末`;
      tempName2 = `${tempData[0]}_期初`;
    } else if (ItmeTemplateKey === 'bqsq') {
      tempName1 = `${tempData[0]}_本期`;
      tempName2 = `${tempData[0]}_上期`;
    }
    return { tempName1, tempName2 };
  };

  const batchVerifyRecalFun = async (isAudio: boolean, rundata?: string) => {
    // let allTidData = [];
    let loadingText = '';
    let batchParams: any = {}
    if (isAudio) {
      batchParams = {
        dbname,
        data_id: '',
        tids: [cpasTableTid.current],
        cpasTableType: 'fs',
      }
      loadingText = '正在勾稽重算...';
    } else {
      loadingText = '正在批量勾稽重算...';
      const resTidData = await getallTidsList(true);
      if (resTidData.resTid?.length) {
        // allTidData = resTidData.resTid;
        batchParams = {
          dbname,
          data_id: '',
          tids: resTidData.resTid,
          cpasTableType: 'fs',
          bsInfo: {
            bsType: "ss",
            isAll: true
          }
        }

      }
    }
    setSpinLoad(true);
    setLoadingContent(loadingText);
    const res: any = await batchVerifyRecal(batchParams);
    if (res.success) {
      if (res.data.errorTotal === 0) {
        notify(`${loadingText},成功！`, 'success', 2000);
      } else {
        const reName = res.data.processError.map((item: any) => item.name).join(';');
        notify(`【${reName}】，勾稽重算失败。`, 'warning', 4000);
      }
      antTabsTabPaneDetail(slectYearDataRef.current.yearStr);
      await loadTableByServerData(rundata || cpasTableName);
    } else {
      notify(`${loadingText},失败！`, 'error', 4000);
    }
    setSpinLoad(false);
    setLoadingContent(' ');
  };

  const cpasTableReloadBatch = async (isAudio: boolean, data_idCan: string = '') => {
    const tempAllData = [...biaoAllData];
    const allParameters: any = {
      sqlApiName: 'account.ssph',
      origin: '试算平衡',
      actionCol: 2,
      paramsData: [],
    };
    tempAllData.forEach((item: any, index: number) => {
      if (index > 4) return;
      if (item.propsData) {
        delete item.propsData.tableRiCurrency;
        if (isAudio) {
          if (item.propsData.templateKey) {
            const resChange = onRadioChangeFor(
              item.propsData.tableName,
              item.propsData.templateKey,
            );
            const audioTable1 = `${data_idCan || slectYearDataRef.current.yearStr}_${resChange?.tempName1
              }`;
            const audioTable2 = `${data_idCan || slectYearDataRef.current.yearStr}_${resChange?.tempName2
              }`;
            if (audioTable1 === cpasTableName) {
              allParameters.paramsData.push({ ...item.propsData, tableName: resChange.tempName1 });
            }
            if (audioTable2 === cpasTableName) {
              allParameters.paramsData.push({ ...item.propsData, tableName: resChange.tempName2 });
            }
          } else {
            const audioTable = `${data_idCan || slectYearDataRef.current.yearStr}_${item.propsData.tableName
              }`;
            if (audioTable === cpasTableName) {
              allParameters.paramsData.push(item.propsData);
            }
          }
        } else {
          if (item.propsData.templateKey) {
            const resChange = onRadioChangeFor(
              item.propsData.tableName,
              item.propsData.templateKey,
            );
            // delete item.propsData.templateKey;
            allParameters.paramsData.push({ ...item.propsData, tableName: resChange.tempName1 });
            allParameters.paramsData.push({ ...item.propsData, tableName: resChange.tempName2 });
          } else {
            // delete item.propsData.templateKey;
            allParameters.paramsData.push(item.propsData);
          }
        }
      }
    });
    try {
      setSpinLoad(true);
      setLoadingContent('数据刷新中...');
      const res: any = await reloadBatchDataRecalculateFs({
        dbname,
        allParameters,
        negationRow,
        data_id: data_idCan || slectYearDataRef.current.yearStr,
      });
      if (res.success) {
        if (res.data.errorTotal === 0) {
          notify('批量刷新成功！', 'success', 2000);
        } else {
          const reName = res.data.processError.map((item: any) => item.name).join(';');
          notify(`【${reName}】，刷新失败。`, 'warning', 4000);
        }
        await batchVerifyRecalFun(isAudio);
        setSpinLoad(false);
        setLoadingContent(' ');
      } else {
        setSpinLoad(false);
        setLoadingContent(' ');
        notify(`【${res.msg}】，刷新失败。`, 'warning', 4000);
      }
    } catch (error) {
      setSpinLoad(false);
      setLoadingContent(' ');
      notify('刷新失败！', 'warning', 2000);
    }
  };

  /**
   * cpas表格数据存储到线上
   */
  async function saveToServer() {
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      try {
        // const res = await realrealHandSonGridRefRef.saveToServer(cpasTableName, CPASTableType);
        const Md5_16Str = Md5_16(cpasTableName);
        await changeCrticulationVerify(realrealHandSonGridRefRef);
        const res = await realrealHandSonGridRefRef.saveToServer(cpasTableName, 'fs', Md5_16Str);
        if (res) {
          const serverData = await realrealHandSonGridRefRef.loadTableByServer(cpasTableName);
          await realrealHandSonGridRefRef.reloadTable(serverData, 'fs', null, true);
          const dataGrid = realrealHandSonGridRefRef.getCpasTableGrid();
          setServerDataLen(dataGrid.data.length);
          notify(`保存成功！`, 'success', 2000);
          antTabsTabPaneDetail(slectYearDataRef.current.yearStr);
          return true;
        }
        return false;
      } catch (error) {
        notify(`保存失败！`, 'error', 2000);
        return false;
      }
    }
    return false;
  }
  // 保存并刷新
  const saveAndReload = async () => {
    setLoadingContent('正在保存数据...');
    setSpinLoad(true);
    await saveToServer();
    cpasTableReloadBatch(true);
  };

  const importChange = (file: any, self: any) => {
    ImportToTitle(file, self);
  };

  // const exportChange = () => {
  //     ExportToTitle(cpasTableFsRefSS.current);
  // };
  // 刷新事件
  const refreshIcon = () => {
    if (openDetails) {
      setOpenDetails(!openDetails);
    }
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      const dataGrid = realrealHandSonGridRefRef.getCpasTableGrid();
      console.log('数据@@@', dataGrid, serverDataLen);
      if (dataGrid.data.length !== serverDataLen) {
        cpasTableChangePupopRef.current.show();
      } else {
        cpasTableReloadBatch(true);
      }
    }
  };

  // const exportExcel1 = async (isAll: boolean) => {
  //     // console.log('@@@', excelParamsData);
  //     // let tempSignData: any[] = await getDevDataList();
  //     const getIsAddObj: any = window.localStorage.getItem(`试算平衡_资产减值准备情况表_${dbname}`);
  //     const isLocalAdd = JSON.parse(getIsAddObj)?.isADD ?? false;

  //     let changeTableDate: any = [...excelParams.excelInfo];
  //     if (isLocalAdd) {
  //         changeTableDate.push({
  //             cpastableParam: {
  //                 tname: "试算平衡-资产减值准备情况表",
  //                 tempTname: "试算平衡-资产减值准备情况表",
  //                 data_id: "",
  //                 type: "fs",
  //             },
  //             excelSheetName: "资产减值准备情况表",
  //             tableTitle: "资产减值准备情况表",
  //             tableDate: " ",
  //             tableLfDesc: `编制单位： ${bsdw}`,
  //             tableRiDesc: "单位：人民币元",
  //             isExportTableTitle: true,
  //         });
  //     }

  //     let tempExcelParams = { ...excelParams };

  //     // 不传data_id
  //     changeTableDate.forEach((item: any) => {
  //         // item.cpastableParam.data_id = slectYearDataRef.current.yearStr;
  //         item.cpastableParam.tname = `${slectYearDataRef.current.yearStr}_${item.cpastableParam.tempTname}`;
  //         // delete item.cpastableParam.tempTname;
  //     });
  //     const excelParamsData = { ...tempExcelParams, excelInfo: changeTableDate };
  //     const dialog_result = await window.electronComponents.showSaveDialog("xlsx", `${origin}.xlsx`);
  //     if (!dialog_result.canceled) {

  //         const fileData = extractFileInfo(dialog_result.filePath);
  //         const params = {
  //             excelInfo: isAll ? tempExcelData : radioTable,
  //             dbname,
  //             directoryPath: fileData.dirName,
  //             excelFileName: fileData.fileName
  //         };
  //         const url = `/cpasApi/cpasTableEngine/getCpatableToBatchExportExcel`;
  //         const data = await axios.post(url, params);
  //         const tempMsg = 'EBUSY: resource busy or locked, open';
  //         const isTrue = data.data.msg.includes(tempMsg);
  //         if (isTrue) {
  //             return {
  //                 code: data.data.code,
  //                 msg: "文件已被程序打开，需要关闭已被打开的文件。",
  //                 ok: data.data.data,
  //                 type: '导出'
  //             };
  //         }
  //         return {
  //             code: data.data.code,
  //             msg: data.data.msg,
  //             ok: data.data.data,
  //             type: '导出'
  //         };
  //     }
  //     return {
  //         code: 404,
  //         msg: '取消了选择路径！',
  //         ok: false,
  //         type: '取消'
  //     };
  // }

  // 打开勾稽校验详情
  const openDetail = async () => {
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      const verifyData = await realrealHandSonGridRefRef.articulationVerifyService
        .artParseResultList;
      setResultListData({
        verifyResult: verifyData,
        isBackAll: false,
      });
    } else {
      notify(`获取verifyData失败！`, 'error', 2000);
    }
    setOpenDetails(true);
  };
  // 关闭勾稽校验详情
  const closeDetail = () => {
    setOpenDetails(!openDetails);
  };

  const exportExcel = async (isAll: boolean = false) => {
    const getIsAddObj: any = window.localStorage.getItem(
      `试算平衡_资产减值准备情况表_${dbname}_${slectYearDataRef.current.yearStr}`,
    );
    const isLocalAdd = JSON.parse(getIsAddObj)?.isADD ?? false;
    const tempExcelData: any = [...excelParams];
    if (isLocalAdd) {
      tempExcelData.push({
        cpastableParam: {
          tname: '试算平衡-资产减值准备情况表',
          tempTname: '试算平衡-资产减值准备情况表',
          data_id: '',
          type: 'fs',
        },
        excelSheetName: '资产减值准备情况表',
        tableTitle: '资产减值准备情况表',
        tableDate: ' ',
        tableLfDesc: `编制单位： ${bsdw}`,
        tableRiDesc: '单位：人民币元',
        isExportTableTitle: true,
        isColumnNum: true,
        isBatchExport: true,
      });
    }
    tempExcelData.forEach((item: any) => {
      // item.cpastableParam.data_id = slectYearDataRef.current.yearStr;
      item.cpastableParam.tname = `${slectYearDataRef.current.yearStr}_${item.cpastableParam.tempTname}`;
      item.signDirection = 'vertical';
      // delete item.cpastableParam.tempTname;
    });

    let radioTable: any = [];
    if (isAll) {
      radioTable = tempExcelData.filter((item: any) => {
        return item.isBatchExport;
      });
    } else {
      radioTable = tempExcelData.filter((item: any) => {
        return item.cpastableParam.tname === cpasTableName;
      });
    }
    console.log(tempExcelData, radioTable, '@@@   tempExcelData');

    // 1、单个导出文件名称：未审财务报表+功能页签名，审定财务报表+功能页签名，试算平衡表：年度—试算平衡表—页签名—期初/期末；
    // 2、批量导出：未审财务报表、审定财务报表、年度—试算平衡表；
    let xlsxName: any = `${slectYearDataRef.current.yearStr}-试算平衡表.xlsx`;
    if (!isAll) {
      let tempName: string = '';
      if (templateKey) {
        if (templateKey === 'qmqc') {
          if (value === 1) {
            tempName = `期末`;
          } else {
            tempName = `期初`;
          }
        } else if (templateKey === 'bqsq') {
          if (value === 1) {
            tempName = `本期`;
          } else {
            tempName = `上期`;
          }
        }
      }

      xlsxName = `${slectYearDataRef.current.yearStr}-试算平衡表-${CPASTableTabName}-${tempName}.xlsx`;
    }
    const dialog_result = await window.electronComponents.showSaveDialog('xlsx', xlsxName);
    // const resultPath = await window.electronComponents.openDirectoryDialog();
    if (!dialog_result.canceled) {
      // 不传data_id
      // const excelParamsData = { ...tempExcelParams, excelInfo: changeTableDate };
      const fileData = extractFileInfo(dialog_result.filePath);
      const params = {
        dbname,
        excelInfo: radioTable,
        directoryPath: fileData.dirName,
        excelFileName: fileData.fileName,
      };
      // console.log(params, '@@@ params');
      // console.log(JSON.stringify(params), 'params---');
      const url = `/cpasApi/cpasTableEngine/getCpatableToBatchExportExcel`;
      const data = await axios.post(url, params);
      if (data.data?.data?.code) {
        return {
          code: data.data.data.code,
          msg: data.data.data.msg,
          ok: data.data.data.ok,
          type: '导出',
        };
      }
      const tempMsg = 'EBUSY: resource busy or locked, open';
      const isTrue = data.data.msg.includes(tempMsg);
      if (isTrue) {
        return {
          code: data.data.code,
          msg: '文件已被程序打开，需要关闭已被打开的文件。',
          ok: data.data.ok,
          type: '导出',
        };
      }
      return {
        code: data.data.code,
        msg: data.data.msg,
        ok: data.data.data,
        type: '导出',
      };
    }
    return {
      code: 404,
      msg: '取消了选择路径！',
      ok: false,
      type: '取消',
    };
  };

  const batchExport = async (isTemp: boolean) => {
    const res = await exportExcel(isTemp);
    console.log(res, '@@@');

    if (res.type === '导出') {
      if (res.ok) {
        notify(`导出成功！`, 'success', 2000);
      } else {
        PopupComponentsRef.current.show({
          title: '提示信息',
          content: res.msg,
          cancelText: '取消',
          okText: '确定',
          okCallback: () => {
            PopupComponentsRef.current.closeDia();
          },
        });
      }
    }
  };

  const changeYearInit = async (yearStr: any, tabsSS: string) => {
    if (tableName) {
      const yearTableName = joinYearAndTable(yearStr, tableName);
      const msg = yearTableName;
      const isName = msg.includes('试算平衡-资产减值准备情况表');
      let tabStatus = '';
      if (!isName) {
        const auditAdjustId: any = window.localStorage.getItem(`selectDefaultSsph_${dbname}`);
        const tempYear = JSON.parse(auditAdjustId)?.ssphYearID ?? sjnd;
        const res = await getfindDesignTableName({
          design_tableName: `${tempYear}_试算平衡-资产减值准备情况表`,
          dbname,
        });
        if (res.data) {
          tabStatus = 'addTab';
        }
      }
      return await getChangeyearInitTemplate(!isName, yearTableName, yearStr, tabStatus, tabsSS);
    }
  };
  /**
   * 下拉框选择事件
   */

  const onSelectionData = async (e: any) => {
    const selectDefaultIDs = { ssphYearID: e.selectedItem.Data_ID };
    // 本地存储 持久化数据
    window.localStorage.setItem(`selectDefaultSsph_${dbname}`, JSON.stringify(selectDefaultIDs));
    setSelectYearData({
      yearStr: e.selectedItem.Data_ID,
      index: e.selectedItem.index,
    });
    setValue(1);
    slectYearDataRef.current.index = e.selectedItem.index;
    slectYearDataRef.current.yearStr = e.selectedItem.Data_ID;

    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      realrealHandSonGridRefRef.resetTable('fs');
    }
    await changeYearInit(e.selectedItem.Data_ID, 'tableSSYear');
  };

  const changeTableByServerData = async (serverDataTable: string) => {
    setLoadingContent('加载中...');
    setSpinLoad(true);
    // debugger
    const res = await loadTableByServerData(serverDataTable);
    if (res?.success) {
      await loadRowsMapData();
      await loadColumnsMapData();
      setSpinLoad(false);
      changeIsInitBtn();
    }
    setSpinLoad(false);
  };

  /**
   * 单选事件
   */
  const onRadioChange = async (valueNumber: any) => {
    setValue(valueNumber);
    const tempData = tableName.split('_');
    let tempName: string = '';
    if (templateKey === 'qmqc') {
      if (valueNumber === 1) {
        tempName = `${tempData[0]}_期末`;
      } else {
        tempName = `${tempData[0]}_期初`;
      }
    } else if (templateKey === 'bqsq') {
      if (valueNumber === 1) {
        tempName = `${tempData[0]}_本期`;
      } else {
        tempName = `${tempData[0]}_上期`;
      }
    }
    if (tempName) {
      if (slectYearDataRef.current.yearStr) {
        tempName = joinYearAndTable(slectYearDataRef.current.yearStr, tempName);
        setSpinLoad(true);
        changeTableByServerData(tempName);
      }
    }

    return tempName;
    // const dataGrid = realrealHandSonGridRefRef.getCpasTableGrid();
    // console.log(dataGrid);
  };

  /**
   *
   * @param nameKey 切换Tabs 的名字。
   * @returns
   */
  const changeTemplete = (nameKey: string) => {
    console.log(nameKey, '@@@');

    if (nameKey === 'qmqc') {
      return (
        <Radio.Group
          onChange={(e) => {
            onRadioChange(e.target.value);
          }}
          value={value}
        >
          <Radio value={1}>期末</Radio>
          <Radio value={2}>期初</Radio>
        </Radio.Group>
      );
    } else if (nameKey === 'bqsq') {
      return (
        <Radio.Group
          onChange={(e) => {
            onRadioChange(e.target.value);
          }}
          value={value}
        >
          <Radio value={1}>本期</Radio>
          <Radio value={2}>上期</Radio>
        </Radio.Group>
      );
    }
    return <div />;
  };

  const useEffectFun = async () => {
    setLoadingContent('正在获取年度...');
    setSpinLoad(true);
    const resYear = await fetchGetYearData();
    if (resYear.success) {
      setSpinLoad(false);
      changeYearInit(resYear.data.yearStr, 'tableSS');
    } else {
      setSpinLoad(false);
      setLoadingContent(' ');
    }
  };
  useEffect(() => {
    if (!isInitBtn) {
      useEffectFun();
    }
  }, []);

  const pathnameUseEffectFun = async (runName: string, runYear: string) => {
    setLoadingContent('正在获取年度...');
    setSpinLoad(true);
    const resYear = await fetchGetYearData();
    if (resYear.success) {
      setSpinLoad(false);
      if (tableName) {
        const yearTableName = runName;
        const msg = yearTableName;
        const isName = msg.includes('试算平衡-资产减值准备情况表');
        getChangeyearInitTemplate(!isName, yearTableName, runYear, 'addTab', 'tableSS');
      }
    } else {
      setSpinLoad(false);
      setLoadingContent(' ');
    }
  };

  useEffect(() => {
    if (pathname === '/ReportSys/trialSys/trialBalance' && query.tableName) {
      const tempTableName = query.tableName.split('_');
      setValue(radioVal);
      pathnameUseEffectFun(query.tableName, tempTableName[0]);
    }
  }, [pathname, query]);

  useImperativeHandle(ref, () => ({
    pathnameRunFun: async (runName: string, runYear: string) => {
      console.log(isInitBtn, '@@@');
      setLoadingContent('正在获取年度...');
      setSpinLoad(true);
      await fetchGetYearData();
      setSpinLoad(false);
      setLoadingContent(' ');
    },
    CPASInit: async (rundata: any, isBatch: boolean = false) => {
      const resYear = await fetchGetYearData();
      if (resYear.success) {
        console.log(rundata);
        await changeTableByServerData(rundata);
        if (isBatch) {
          await batchVerifyRecalFun(false, rundata);
        }
      }
    },
    clearDesignTableName: async (tempTableName: any) => {
      const realrealHandSonGridRefRef = getRealCPASTableRef();
      if (realrealHandSonGridRefRef) {
        return await realrealHandSonGridRefRef.removeTableByServer(`${tempTableName}`, '', 'fs');
      }
    },
    CPASOpenDetail: () => {
      openDetail();
    },
  }));

  const getallTidsList = async (isaaaa: boolean = false) => {
    const res = await getCpasAllTids({
      dbname,
      originTableName: '试算平衡-',
      isAllTid: isaaaa,
    });
    console.log(res, '@@@ CpasAllTids');
    if (res.success) {
      const resMap = res.data.map((item: any) => item?.tid).filter((item: any) => item);
      return {
        resTid: resMap,
        resData: res.data,
      };
    } else {
      notify('获取AllTids列表失败!', 'error', 4000);
    }
    return {
      resTid: [],
      resData: [],
    };
  };

  const batchClearFun = async () => {
    setSpinLoad(true);
    setLoadingContent('正在批量清空数据...');
    const allTidData = await getallTidsList(true);
    if (allTidData.resTid.length) {
      const res: any = await batchClearData({
        dbname,
        data_id: '',
        tids: allTidData.resTid,
        cpasTableType: 'fs',
      });
      if (res.success) {
        if (res.data.errorTotal === 0) {
          notify('批量清空数据,成功！', 'success', 2000);
        } else {
          const reName = res.data.processError.map((item: any) => item.name).join(';');
          notify(`【${reName}】，清空数据失败。`, 'warning', 4000);
        }
        antTabsTabPaneDetail(slectYearDataRef.current.yearStr);
        await loadTableByServerData(cpasTableName);
      } else {
        notify('批量清空数据,失败！', 'error', 4000);
      }
      setSpinLoad(false);
      setLoadingContent(' ');
    }
    setSpinLoad(false);
    setLoadingContent(' ');
  };

  const batchClearGSFun = async () => {
    setSpinLoad(true);
    setLoadingContent('正在批量清空公式...');
    const allTidData = await getallTidsList(true);
    if (allTidData.resTid.length) {
      const res: any = await batchClearGSData({
        dbname,
        data_id: '',
        tids: allTidData.resTid,
        cpasTableType: 'fs',
      });
      if (res.success) {
        if (res.data.errorTotal === 0) {
          notify('批量清空公式,成功！', 'success', 2000);
        } else {
          const reName = res.data.processError.map((item: any) => item.name).join(';');
          notify(`【${reName}】，清空公式失败。`, 'warning', 4000);
        }
        antTabsTabPaneDetail(slectYearDataRef.current.yearStr);
        await loadTableByServerData(cpasTableName);
      } else {
        notify('批量清空公式,失败！', 'error', 4000);
      }
      setSpinLoad(false);
      setLoadingContent(' ');
    }
    setSpinLoad(false);
    setLoadingContent(' ');
  };

  const changeSelectedRow = (rowsData: any) => {
    let beTempResult = '';
    if (rowsData?.beVerifyFormat?.startsWith('=')) {
      beTempResult = rowsData?.beVerifyFormat.substring(1);
    } else {
      beTempResult = rowsData?.beVerifyFormat;
    }
    const { beVerifyIsNA, verifyIsNA } = rowsData;
    const renderNoneFormat = () => {
      return (<span style={{ color: "red", width: "auto" }}>【无效公式】</span>)
    }
    const beFormatText = pushNumberData(rowsData?.beVerifiedFormulaResult);
    const beTempText = () => {
      return (
        <div className="ss-verify-box"><span className="ss-formula-li" dangerouslySetInnerHTML={{ __html: beTempResult }} /> = {beVerifyIsNA ? `${beFormatText.formattedPrice}(N/A)` : beFormatText.formattedPrice}</div>
      )
    };

    let tempResult = '';
    if (rowsData?.verifyFormat?.startsWith('=')) {
      tempResult = rowsData?.verifyFormat.substring(1);
    } else {
      tempResult = rowsData?.verifyFormat;
    }

    const formatText = pushNumberData(rowsData?.verifyFormulaResult);
    const tempText = () => {
      return (
        <div className="ss-verify-box"><span className="ss-formula-li" dangerouslySetInnerHTML={{ __html: tempResult }} /> = {verifyIsNA ? `${formatText.formattedPrice}(N/A)` : formatText.formattedPrice}</div>
      )
    };
    rowsData = {
      ...rowsData,
      beVerifiedFormulaShowText: beTempText(),
      verifyFormulaShowText: tempText(),
    };
    setSelectedRowData(rowsData);
  };

  const onSelectionChangedRow = useCallback((e: any) => {
    const { selectedRowsData, selectedRowKeys } = e;
    changeSelectedRow(selectedRowsData[0]);
    setSelectedKey(selectedRowKeys);
  }, []);

  const parseCross = (formulaList: any): any[] => {
    const IN_CELLS: any[] = [];

    formulaList.forEach((formulaItem: any) => {
      const {
        beVerifiedFormulaResultList,
        fullFormulaResultFormat,
        isForce,
        number,
        operation,
        tableName: tName,
        type,
        beVerifiedFormula,
      } = formulaItem;
      if (typeof beVerifiedFormula === 'string' && beVerifiedFormula.includes('V_CROSS')) {
        for (let i = 0; i < beVerifiedFormulaResultList.length; i++) {
          const {
            formula: beFormula,
            formulaFormat: beFormulaFormat,
            value: beValue,
            result,
            verifyItem,
          } = beVerifiedFormulaResultList[i];
          const {
            formula: verifyFormula,
            formulaFormat: verifyFormulaFormat,
            value: verifyValue,
          } = verifyItem;
          const verifyParseItem = {
            beVerifiedFormula: beFormulaFormat,
            beVerifyFormat: beFormulaFormat,
            verifyFormat: verifyFormulaFormat,
            verifyFormula: verifyFormula,
            beVerifiedFormulaResult: beValue,
            verifyFormulaResult: verifyValue,
            fullFormulaResult: result,
            fullFormulaResultFormat: '2',
            id: nanoid10(),
            isForce,
            number: `${number}_${i + 1}`,
            operation,
            tableName: tName,
            type,
            tempID: nanoid10(),
          };
          IN_CELLS.push(verifyParseItem);
        }
      } else {
        IN_CELLS.push(formulaItem);
      }
    });

    return IN_CELLS;
  };

  // 校验结果刷新
  const loadTableByServerDataVerifyByRMap = async (paramsObj: {
    serverName: string;
    curTid: string;
  }) => {
    setSpinLoad(true);
    setLoadingContent('正在获取校验结果...');
    const realrealHandSonGridRefRef = getRealCPASTableRef();
    if (realrealHandSonGridRefRef) {
      try {
        // 重算一下当前表
        // await batchVerifyRecal({
        //   dbname,
        //   data_id: '',
        //   tids: [paramsObj.curTid],
        //   cpasTableType: 'fs',
        // });
        // serverData = await realrealHandSonGridRefRef.loadTableByServer(paramsObj.serverName);
        const data = realrealHandSonGridRefRef.hot.getData();
        const cellsMeta = realrealHandSonGridRefRef.filterMetas();
        cpasTableAllRowsMapsData.current = getAllRowsMaps(data);
        const resByRMap = await getVerifyByRMap({
          dbname,
          dataId: slectYearDataRef.current.yearStr,
          tid: paramsObj.curTid,
        });
        cpasTableVerifyData.current = resByRMap.data;
        const computedCellsMeta = CellsMetaUpdateCPASTableData(
          cellsMeta,
          cpasTableAllRowsMapsData.current,
          resByRMap.data,
        );
        for (let index = 0; index < computedCellsMeta.length; index++) {
          const element = computedCellsMeta[index];
          if (element.col === 1) {
            realrealHandSonGridRefRef?.hot.setCellMeta(element.row, element.col, 'custom', {
              ...element.custom,
            });
          }
        }
        realrealHandSonGridRefRef?.hot.render();

        // 重新拿一下
        const verifyData = await realrealHandSonGridRefRef.loadVerifyByServer(paramsObj.curTid);
        const fsParams = {
          dbname,
          tid: paramsObj.curTid,
          type: 'fs',
        };
        const lodaTableZl = await queryVerifyStatefs(fsParams);
        if (lodaTableZl.code === 200) {
          realrealHandSonGridRefRef.setVerifyData(verifyData);
          setResultListData({
            verifyResult: verifyData.artParseResultList,
            isBackAll: false,
          });
        }
        await changeCrticulationVerify(realrealHandSonGridRefRef);
        await antTabsTabPaneDetail(slectYearDataRef.current.yearStr);
        setSpinLoad(false);
        notify(`获取该表校验结果成功！`, 'success', 2000);
      } catch (error) {
        notify(`获取该表校验结果失败:【${paramsObj.serverName}】！`, 'warning', 2000);
        setSpinLoad(false);
      }
    }
  };
  return (
    <div className="commonCpasTableTrialBox">
      {/* {spinLoad && <SpinLoading loadString="" />} */}
      {/* <FormsTitle titleYearData={selectYearData}></FormsTitle> */}
      <PageLoading isOpen={spinLoad} isMaskClose={false} content={loadingContent} width={200} />
      <div className="btnsTools">
        <Button
          className="defaultBtnWhite purpleBtnUI"
          onClick={() => {
            loadTableByServerDataVerifyByRMap({
              serverName: cpasTableName,
              curTid: cpasTableTid.current,
            });
          }}
          text="校验结果刷新"
        />
        <Button
          type="default"
          className="defaultBtn"
          onClick={async () => {
            setLoadingContent('正在保存数据...');
            setSpinLoad(true);
            const resSave = await saveToServer();
            if (resSave || !resSave) {
              setTimeout(() => {
                setSpinLoad(false);
              }, 500);
            }
          }}
          text="保存"
        />
        <Button
          className="defaultBtnWhite purpleBtnUI"
          onClick={() => {
            setShowMenuToolBar(!showMenuToolBar);
          }}
          text="模板设计"
        />

        {/* <Button
                className="defaultBtnWhite purpleBtnUI"
                onClick={() => {
                    cpasTableReloadBatch(false, slectYearDataRef.current.yearStr);
                }} text='批量刷新'
            /> */}

        {/* <Button
                className="defaultBtnWhite"
                onClick={() => {
                    openDetail();
                }} text='校验详情'
            /> */}
        {/* <DropDownButton
                text='文件'
                style={{ height: "30px", marginRight: "8px" }}
                dropDownOptions={{
                    width: 120
                }}
                onItemClick={(e: any) => {
                }}
            >
                <ButtonItem
                    disabled={exportExcelBtn}
                    onClick={async () => {
                        notify(`批量导入正在开发中。。。`, "warning", 2000);
                    }}
                    render={() => (<>批量导入</>)}
                />
                <ButtonItem
                    disabled={exportExcelBtn}
                    onClick={async () => {
                        setExportExcelBtn(true);
                        const res = await exportExcel();
                        if (res.type === '导出') {
                            if (res.ok) {
                                notify(`导出成功！`, "success", 2000);
                            } else {
                                notify(`导出失败！`, "error", 2000);
                            }
                        }
                        setExportExcelBtn(false);

                    }}
                    render={() => (<>批量导出</>)}
                />
            </DropDownButton> */}
        {/* <Button
                className="defaultBtnWhite"
                onClick={async () => {
                    const res = await exportExcel();
                    if (res.type === '导出') {
                        if (res.ok) {
                            notify(`导出成功！`, "success", 2000);
                        } else {
                            notify(`导出失败！`, "error", 2000);
                        }
                    }
                }} text='批量导出'
            /> */}
        <DropDownButton
          style={{ height: '30px', margin: '0px 8px 0 4px' }}
          text="批量"
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={async (e: any) => {
            if (e.itemData === '批量勾稽重算') {
              batchVerifyRecalFun(false);
            } else if (e.itemData === '批量清空数据') {
              batchClearFun();
            } else if (e.itemData === '批量刷新') {
              cpasTableReloadBatch(false, slectYearDataRef.current.yearStr);
            } else {
              batchClearGSFun();
            }
          }}
          items={['批量勾稽重算', '批量清空数据', '批量刷新', '批量清空公式']}
        />
        <DropDownButton
          style={{ height: '30px', margin: '0px 8px 0 4px' }}
          text="导出"
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={async (e: any) => {
            batchExport(e.itemData === '批量导出成果');
          }}
          items={['单个导出成果', '批量导出成果']}
        />

        <DropDownButton
          style={{ height: '30px', margin: '4px' }}
          text="模板"
          dropDownOptions={{
            width: 120,
          }}
          onItemClick={async (e: any) => {
            if (e.itemData === '切换模板') {
              const data = await getSeekAuditReportTemplate({ zcbfid });
              console.log('当前模板：', data.data.AuditReportTemplate);
              const templateName = data.data.AuditReportTemplate;
              changeTemplatePopupRef.current.showTemplate({ templateName });
            } else {
              saveTemplatePopupRef.current.showTemplate();
            }
          }}
          items={['切换模板', '保存模板']}
        />
        <div className="boxRight" />

        <Button
          className="defaultReloadBtnWhite"
          disabled={tabsIndex > 5}
          render={() => <CpasIcon type="icon-refresh" fontSize={16} />}
          onClick={() => {
            refreshIcon();
          }}
        />
      </div>
      <div className="BalanceLRXJBCRadio">
        <div style={Divstyle}>
          <div>年度：</div>
          <SelectBox
            width={150}
            dataSource={showYaerData.current}
            displayExpr="displayName"
            valueExpr="displayName"
            value={showYaerData.current[selectYearData.index || 0]?.displayName ?? ' '}
            onSelectionChanged={onSelectionData}
            dropDownOptions={{ width: '200px' }}
          />
        </div>
        {changeTemplete(templateKey)}
      </div>
      <div className="commonCpasTableTrial">
        <CpasTableFs
          tabGroup="fs-tab"
          tabLevel={2}
          ieType="json,draft"
          numberZeroReplace={cpasTableZeroReplace}
          type={'fs'}
          name={cpasTableName}
          mapRowsList={rowsMapList}
          mapColumnsList={columnsMapList}
          isShowMenuToolBar={showMenuToolBar}
          verifyMode={true}
          notes={{ tid: cpasTableTid.current }}
          isTest={true}
          ref={cpasTableFsRefSS}
          // tableDate={titleYearStr}
          tableDate={' '}
          tableTitle={titleName}
          tableRiDesc={`单位：${tableRiCurrency}`}
          tableLfDesc={`编制单位：${bsdw}`}
          draftSheetName={titleName}
          afterOnCellMouseDown={async (a, arr, cb) => {
            if (arr.col === 1) {
              const tempNameData = cpasTableAllRowsMapsData.current[arr.row - 1];
              if (tempNameData) {
                const tempObjData = cpasTableVerifyData.current[tempNameData];
                if (tempObjData && !tempObjData?.verify) {
                  const tempTidData = tempObjData?.itemList.map(
                    (item: { tid: string }) => item.tid,
                  );
                  function generateVerifyData(tempTidData: string[], objVerify: any) {
                    return tempTidData.flatMap((key) => {
                      const obj = objVerify[key];
                      return obj
                        ? obj.artParseResultList.map((item: any) => ({
                          ...item,
                          tableName: obj.tableName,
                          tid: obj.tid,
                          tempID: Guid.newGuid() + '_Verify',
                        }))
                        : [];
                    });
                  }
                  const resVerify = await getVerifyDataList({
                    dbname: dbname,
                    tids: tempTidData,
                    verifyType: false,
                    isNeedFormat: true,
                  });
                  if (resVerify.success) {
                    const tempVerifyData = generateVerifyData(tempTidData, resVerify.data);
                    if (
                      !tempVerifyData ||
                      (Array.isArray(tempVerifyData) && tempVerifyData.length === 0)
                    ) {
                      return notify('未找到校验错误信息,请尝试【校验结果刷新】', 'error', 3000);
                    }
                    console.log(tempVerifyData, '@@@ Verify');
                    const parseVerifyData = parseCross(tempVerifyData);
                    setIsModalTableData(parseVerifyData);
                    setIsShowOpenModal(true);
                    changeSelectedRow(parseVerifyData[0]);
                    setSelectedKey([parseVerifyData[0]?.tempID]);
                  }
                }
              }
            }
          }}
          afterOnArtCellClick={(a, arr, cb) => {
            const realrealHandSonGridRefRef = getRealCPASTableRef();
            if (realrealHandSonGridRefRef) {
              const p: any = [];
              const resultList =
                realrealHandSonGridRefRef.articulationVerifyService.artParseResultList;
              console.log(resultList);
              if (cb !== null && cb[0]) {
                resultList.map((item: any) => {
                  const havePro = item.beVerifiedCoordsMap;
                  console.log(
                    '是否存在该属性',
                    havePro?.hasOwnProperty(cb[0].currentFormula),
                    havePro,
                    cb[0].currentFormula,
                  );

                  if (havePro?.hasOwnProperty(cb[0].currentFormula)) {
                    p.push(item);
                  }
                });
                setResultListData({
                  verifyResult: p,
                  isBackAll: true,
                });
                closeDetail();
              } else {
                return notify('非校验项/已校验通过!', 'error', 2000);
              }
            }
          }}
        />
        <Modal
          open={isShowOpenModal}
          title={'校验结果'}
          footer={null}
          maskClosable={false}
          onCancel={() => {
            setIsShowOpenModal(false);
            setSelectedRowData({});
            setSelectedKey([]);
            setIsModalTableData([]);
          }}
          width={'1000px'}
        >
          <div style={{ height: '600px' }}>
            <DataGrid
              className="devHeadersCenter PaperDevSortableGrid advancedQueryDataGrid"
              dataSource={isModalTableData}
              showBorders={true}
              showRowLines={true}
              id={'verify-shi-suan'}
              showColumnLines={true}
              rowAlternationEnabled={true}
              allowHeaderFiltering={false}
              allowSorting={false}
              width="100%"
              height="calc(100% - 160px) "
              keyExpr="tempID"
              onSelectionChanged={onSelectionChangedRow}
              selectedRowKeys={selectedKey}
            >
              <Scrolling mode="virtual" rowRenderingMode="virtual" renderAsync={true} />
              <Selection mode="single" />
              <Paging enabled={false} />
              <Column caption="表名" dataField="tableName" dataType="string" alignment="left" />
              <Column
                caption="校验类型"
                dataField="type"
                dataType="string"
                width={100}
                alignment="left"
                cellRender={(e) => {
                  const { data } = e;
                  let tempText: any = null;
                  if (data.type === '1') {
                    tempText = '表内校验';
                  } else if (data.type === '2') {
                    tempText = '表间校验';
                  } else if (data.type === '3') {
                    tempText = '与报表校验';
                  } else if (data.type === '4') {
                    tempText = '交叉校验';
                  } else {
                    tempText = '-';
                  }
                  return <div>{tempText}</div>;
                }}
              />
              <Column
                caption="结果"
                dataField="fullFormulaResult"
                width={60}
                alignment="center"
                cellRender={(e) => {
                  const { data } = e;
                  // let tempText: any = null;
                  if (data.fullFormulaResult) {
                    return <CheckCircleOutlined style={{ color: 'greenyellow' }} />;
                  }
                  return <CloseCircleOutlined style={{ color: 'red' }} />;
                }}
              />
              <Column
                caption="结果类型"
                dataField="fullFormulaResultFormat"
                dataType="string"
                width={100}
                alignment="left"
                cellRender={(e) => {
                  const { data } = e;
                  let tempText: any = null;
                  if (data.fullFormulaResultFormat === '1') {
                    tempText = '逻辑不符';
                  } else if (data.fullFormulaResultFormat === '2') {
                    tempText = '差异数';
                  } else if (data.fullFormulaResultFormat === '3') {
                    tempText = '无法校验';
                  } else {
                    tempText = '-';
                  }
                  return <div>{tempText}</div>;
                }}
              />
              <Column
                caption="被校验项值"
                dataType="number"
                dataField="beVerifiedFormulaResult"
                alignment="right"
                width={120}
                cellRender={(e) => {
                  const { data } = e;
                  const formatText = pushNumberData(data.beVerifiedFormulaResult);
                  return <div>{formatText.formattedPrice}</div>;
                }}
              />
              <Column
                caption="校验项值"
                dataType="number"
                dataField="verifyFormulaResult"
                alignment="right"
                width={120}
                cellRender={(e) => {
                  const { data } = e;
                  const formatText = pushNumberData(data.verifyFormulaResult);
                  return <div>{formatText.formattedPrice}</div>;
                }}
              />
              <Column
                caption="差异数"
                dataType="number"
                alignment="right"
                width={120}
                cellRender={(e) => {
                  const { data } = e;
                  let formatText: any = {};
                  if (data.fullFormulaResultFormat === '2') {
                    function subtract(a, b) {
                      const result = new BigNumber(a).minus(b);
                      return pushNumberData(result);
                    }
                    formatText = subtract(data.verifyFormulaResult, data.beVerifiedFormulaResult);
                  }

                  return <div>{formatText?.formattedPrice ?? ''}</div>;
                }}
              />
            </DataGrid>
            <div
              style={{
                height: '150px',
                marginTop: '10px',
                border: '1px solid #bbbbbb',
                overflowY: 'auto',
                borderRadius: '8px',
              }}
            >
              <div style={{
                display: 'flex',
                borderBottom: '1px solid #bbbbbb',
              }}>
                <div style={{ width: '130px', textAlign: 'right' }}>表名：</div>
                <div style={{ flex: 1 }}>{selectedRowData.tableName} </div>
              </div>

              <div style={{
                display: 'flex',
                borderBottom: '1px solid #bbbbbb',
              }}>
                <div style={{ width: '130px', textAlign: 'right' }}>被校验项（本表）：</div>
                <div style={{ flex: 1 }}>{selectedRowData.beVerifiedFormulaShowText}
                </div>
              </div>
              <div style={{
                display: 'flex',
              }}>
                <div style={{ width: '130px', textAlign: 'right' }}>校验项：</div>
                <div style={{ flex: 1, }}>{selectedRowData.verifyFormulaShowText}
                </div>
              </div>
            </div>
          </div>
        </Modal>
      </div>

      <CpasTableChangePupop ref={cpasTableChangePupopRef} tableSaveAndReload={saveAndReload} />

      <Details
        isOpen={openDetails}
        handleOpen={closeDetail}
        params={cpasTableFsRefSS?.current?.handsonTableFs}
        result={resultListData.verifyResult}
        isBackAll={resultListData.isBackAll}
        onBackAll={() => {
          setResultListData((oldData: any) => {
            const newData = { ...oldData, isBackAll: false };
            return newData;
          });
        }}
      />

      {/* <CheckDetails
            isOpen={this.state.isOpenDetails}
            handleOpen={this.onShowDetailsModal}
            result={this.state.result}
            onBackAll={this.onBackAll}
            isBackAll={this.state.isBackAll}
            resultList={this.state.resultList}
            params={this.zlTableRef}
        /> */}

      <PopupComponents ref={PopupComponentsRef} />
      <SaveTemplatePopup
        ref={saveTemplatePopupRef}
        okCallback={async (data: any) => {
          console.log(data, '@@@ 保存模板');
          const res: any = await saveTemplateApi({
            dbName: dbname,
            templateName: data,
            type: 'ss',
            tableNames: tableNameGroup,
            dataId: slectYearDataRef.current.yearStr,
          });
          if (res.success) {
            notify('保存成功', 'success', 2000);
          } else {
            notify('保存失败', 'error', 2000);
          }
        }}
        cancelCallback={() => {
          console.log('@@@ ， 取消');
        }}
      />

      <ChangeTemplatePopup
        ref={changeTemplatePopupRef}
        okCallback={async (data: any) => {
          console.log(data, '@@@ 切换模板');
          setLoadingContent('正在切换模板...');
          setSpinLoad(true);
          const yearTableName = joinYearAndTable(slectYearDataRef.current.yearStr, tableName);
          const resTemp: any = await templateInitApi({
            dbName: dbname,
            templateName: data,
            tableNames: tableNameGroup,
            type: 'ss',
            dataId: slectYearDataRef.current.yearStr,
          });
          if (resTemp.success) {
            const resClear = await clearDynamicByMainTable({
              dbname,
              tableRealName: yearTableName,
            });
            if (resClear.success) {
              await batchVerifyRecalFun(false);
              await antTabsTabPaneDetail(slectYearDataRef.current.yearStr);
              cpasChangeSpinAntTabs(false, yearTableName);
              notify(`切换模板成功`, 'success', 2000);
              cpasChangeSpinAntTabs(true, yearTableName);
            }
          } else {
            notify(`${resTemp.msg}`, 'error', 2000);
          }
          setSpinLoad(false);
          setLoadingContent(' ');
        }}
        cancelCallback={() => {
          console.log('@@@ ， 取消');
        }}
        changeData={{
          cloudTempType: '报告模板',
        }}
      />
    </div>
  );
});
export default React.memo(CommonCpasTableSS);
